﻿using System;
using System.Data;
using System.Windows.Forms;
using Home.Haushalt.Lib;
using Infragistics.Win.UltraWinCalcManager.FormulaBuilder;
using System.Drawing;
using Home.Haushalt.Lib.Element;
using Infragistics.Win.UltraWinGrid;
using System.Diagnostics;
using System.Linq;
using System.IO;

namespace Home.Haushalt.Gui
{
    /// <summary>
    /// 
    /// </summary>
    public partial class UcGridFormElement : UcGridForm
    {
        /// <summary></summary>
        private ElementBase _element;

        /// <summary>
        /// 
        /// </summary>
        public UcGridFormElement()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="elementType"></param>
        /// <param name="columnSet"></param>
        /// <param name="layoutName"></param>
        public UcGridFormElement(Type elementType, DefaultColumnSets columnSet, string layoutName)
            : base(columnSet, layoutName)
        {
            _element = ElementBase.Instantiate(elementType);

            Init();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="element"></param>
        /// <param name="columnSet"></param>
        /// <param name="layoutName"></param>
        public UcGridFormElement(ElementBase element, DefaultColumnSets columnSet, string layoutName)
            : base(columnSet, layoutName)
        {
            _element = element;

            Init();
        }

        /// <summary>
        /// 
        /// </summary>
        private void Init()
        {
            InitializeComponent();

            BaseGrid.ContextMenuStrip.Opened += new EventHandler(ContextMenuStrip_Opened);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ContextMenuStrip_Opened(object sender, EventArgs e)
        {
            if (BaseGrid._clickedObject is UltraGridCell || BaseGrid._clickedObject is UltraGrid)
            {

                if (_element.GetType().Equals(Posten.ElementType))
                {
                    int insertIndex = 2;
                    ToolStripMenuItem serieElementItem = new ToolStripMenuItem("Folge-Posten erstellen", global:: Home.Haushalt.Lib.Properties.Resources.element_serie, cmnuPropertyCopySerie_Click);
                    serieElementItem.Enabled = (BaseGrid.Selected.Rows.Count > 0);
                    BaseGrid.ContextMenuStrip.Items.Insert(insertIndex++, serieElementItem);
                }
                else
                    if (_element.GetType().Equals(Member.ElementType) && BaseGrid.Selected.Rows.Count.Equals(1))
                    {
                        int insertIndex = 0;
                        _element.Row = BaseGrid.Selected.Rows[0].ToDataRow();

                        Member memberElement = (Member)_element;

                        //AutoLogin
                        ToolStripMenuItem autoLoginItem = new ToolStripMenuItem("AutoLogin", null, cmnuAutoLogin_Click);
                        autoLoginItem.Enabled = DAO.HFile.AutoLoginExists(_element.ID);
                        BaseGrid.ContextMenuStrip.Items.Insert(insertIndex++, autoLoginItem);

                        //Login merken, User mekren und Link öffnen
                        bool linkFound = !_element.Row[Member.Fields.Link].ToString().Length.Equals(0);
                        bool userFound = !_element.Row[Member.Fields.UserName].ToString().Length.Equals(0);

                        string linkOpenItemText = (linkFound && userFound) ? "Login in die Zwischenablage und URL öffnen" : ((linkFound && !userFound) ? "URL öffnen" : ((!linkFound && userFound) ? "Login in die Zwischenablage" : "Login in die Zwischenablage und URL öffnen"));
                        ToolStripMenuItem linkOpenItem = new ToolStripMenuItem(linkOpenItemText, global:: Home.Haushalt.Gui.Properties.Resources.clipboard, cmnuUserToClipboard_Click);
                        linkOpenItem.Enabled = linkFound || userFound;
                        BaseGrid.ContextMenuStrip.Items.Insert(insertIndex++, linkOpenItem);

                        ////Kennwort mekren
                        //bool passFound = !_element.Row[Member.Fields.Pass].ToString().Length.Equals(0);
                        //ToolStripMenuItem passItem = new ToolStripMenuItem("Kennwort in die Zwischenablage", null, cmnuPassToClipboard_Click);
                        //passItem.Enabled = passFound;
                        //BaseGrid.ContextMenuStrip.Items.Insert(insertIndex++, passItem);

                        //Dokument öffnen wenn vorhanden
                        bool docFound = _element.Row[Member.Fields.DocumentId].ToString() != "0";
                        ToolStripMenuItem docItem = new ToolStripMenuItem("Dokument öffnen", null, cmnuOpenDoc_Click);
                        docItem.Enabled = docFound;
                        BaseGrid.ContextMenuStrip.Items.Insert(insertIndex++, docItem);

                        BaseGrid.ContextMenuStrip.Items.Insert(insertIndex++, new ToolStripSeparator());

                    }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuAutoLogin_Click(object sender, EventArgs e)
        {
            FrmAutoLogin.StartAutoLogin(_element.ID);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuUserToClipboard_Click(object sender, EventArgs e)
        {
            Program.ClipboardMember = (Member)_element;

            string link = _element.Row[Member.Fields.Link].ToString();
            string userName = _element.Row[Member.Fields.UserName].ToString();

            bool linkFound = !link.Length.Equals(0);
            bool userFound = !userName.Length.Equals(0);

            if (userFound)
            {
                Clipboard.SetText(userName);
            }

            if (linkFound)
            {
                Process.Start(link);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuOpenDoc_Click(object sender, EventArgs e)
        {
            string docId = _element.Row[Member.Fields.DocumentId].ToString();
            DataRow row = DAO.GetRows(typeof(Page), "{0} = {1}", Page.Fields.DocumentId, docId).FirstOrDefault();
            if (row != null)
            {
                Page pageObj = new Page(row);
                string filename = "";

                if (pageObj.Row[Page.Fields.SourceFileName] != null &&
                    pageObj.Row[Page.Fields.SourceFileName].ToString().Length > 0 &&
                    File.Exists(pageObj.Row[Page.Fields.SourceFileName].ToString()))
                {
                    filename = row[Page.Fields.SourceFileName].ToString();
                }
                else
                {
                    filename = pageObj.DecryptFilePath;
                }

                try
                {
                    Process.Start(filename);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Datei kann nicht geöffnet werden: " + ex.Message);
                    Journal.Add(this, ex);
                }

            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuPropertyCopySerie_Click(object sender, EventArgs e)
        {
            foreach (UltraGridRow gridRow in BaseGrid.Selected.Rows)
            {
                DataRow selectedRow = gridRow.ToDataRow();
                DataRow newRow = selectedRow.Clone();

                if (newRow[Posten.Fields.SerieId].ToInt().Equals(0) || newRow[Posten.Fields.SerieId].ToInt().Equals(-1))
                {
                    selectedRow[Posten.Fields.SerieId] = newRow[Posten.Fields.SerieId] = Posten.GetNextSerieId();
                }

                BaseGrid.EditElementProperty(newRow);
                //BaseGrid.EditElementProperty(selectedRow);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmGridForm_Load(object sender, EventArgs e)
        {
            if (!LayoutController.IsInDesignMode(this))
            {
                DataBind();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public override void DataBind()
        {
            BaseGrid.DataBind(_element, ColumnSet);

            BaseGrid.LoadLayout(LayoutName);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grid_DoubleClickRow(object sender, Infragistics.Win.UltraWinGrid.DoubleClickRowEventArgs e)
        {
            if (BaseGrid.Selected.Rows.Count > 0)
            {
                BaseGrid.EditElementProperty(BaseGrid.Selected.Rows[0].ToDataRow());
            }
        }

    }
}
